package ru.paswd.marketprice

import android.content.Context
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import ru.paswd.marketprice.api.Api

object Server {
    private var retrofit: Retrofit? = null

    fun withContext(context: Context): Server {
        if (retrofit != null) {
            return this
        }

        val interceptor = HttpLoggingInterceptor()
        interceptor.level = HttpLoggingInterceptor.Level.BODY
        val client = OkHttpClient.Builder()
            .addInterceptor(interceptor).build()
        val gson = GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")
                .create()
        retrofit = Retrofit.Builder()
            .baseUrl(context.getString(R.string.api_url))
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(client)
            .build()

        return this
    }

    fun getApi() = retrofit?.create(Api::class.java)
        ?: throw RuntimeException("Cannot create API object")
}